from rest_framework import pagination
from rest_framework.response import Response
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage


class RangePaginator(Paginator):
    def validate_number(self, number):
        try:
            number = super().validate_number(number)
        except PageNotAnInteger:
            number = 1
        except EmptyPage:
            number = int(number)
            if number < 1:
                number = 1
            if number > self.num_pages:
                number = self.num_pages
        return number


class PageNumberPagination(pagination.PageNumberPagination):
    page_size_query_param = 'size'
    # page_size = 5
    max_page_size = 10
    django_paginator_class = RangePaginator

    def get_paginated_response(self, data):
        return Response({
            'pagination': {
                'total': self.page.paginator.count,
                'size': self.get_page_size(self.request),
                'page': self.page.number
            },
            'results': data,
        })
